/**
 * 
 */
package br.com.fatesg.www.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;

import br.com.fatesg.www.util.ExcecaoInfraEstrutura;
import br.com.fatesg.www.util.HibernateUtil;

/**
 * @author Grupo
 * 
 */
public abstract class DAO<T, PK> {

	Session session;

	public DAO(Session session) {
		this.session = session;
	}

	@SuppressWarnings("unchecked")
	public PK salvar(T t) throws ExcecaoInfraEstrutura {
		session.beginTransaction();
		PK id = (PK) this.session.save(t);
		session.getTransaction().commit();
		session.flush();
		session.close();
		return id;
	}

	public void excluir(T t) throws ExcecaoInfraEstrutura {
		session.beginTransaction();
		this.session.delete(t);
		session.getTransaction().commit();
		session.flush();
		session.close();
	}

	public void atualizar(T t) throws ExcecaoInfraEstrutura {
		session.beginTransaction();
		this.session.merge(t);
		session.getTransaction().commit();
		session.flush();
		session.close();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<T> listar(Class clazz) throws ExcecaoInfraEstrutura {
		if (!session.isOpen()) {
			session = HibernateUtil.getSessionFactory().openSession();
		}
		return this.session.createCriteria(clazz).list();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public T obterPeloId(Class clazz, PK pk) throws ExcecaoInfraEstrutura {
		return (T) session.load(clazz, (Serializable) pk);
	}

	public abstract T obter(PK pk) throws ExcecaoInfraEstrutura;

	public abstract Session getSession();
}
